package com.example.gwlblu;

import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.io.InputStream;
import java.util.UUID;

public class Server extends AppCompatActivity {
    private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Server端和Client端的UUID要一致
    private BluetoothAdapter bluetoothAdapter;
    private final String NAME = "BlueTooth_Socket";//名字可以随便写

    private AcceptThread acceptThread;//后面的accept（）会阻塞，所以要新开线程


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        acceptThread=new AcceptThread();
        acceptThread.start();//开启线程
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(Server.this, String.valueOf(msg.obj), Toast.LENGTH_SHORT).show();
        }
    };

    private class AcceptThread extends Thread {
        private BluetoothServerSocket serverSocket;
        private BluetoothSocket socket;
        private InputStream is;

        public AcceptThread() {
            try {
                //监听有无连接
                serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (Exception e) {
            }
        }

        @Override
        public void run() {
            try {
                socket = serverSocket.accept();//若有监听到有连接，accept给BluetoothSocket
                Log.d("tag", "connected");

                is = socket.getInputStream();

                while (true) {
                    byte[] buffer = new byte[128];
                    int count = is.read(buffer);
                    //子线程里不能直接Toast，利用handler
                    Message msg = new Message();
                    msg.obj = new String(buffer, 0, count, "UTF-8");
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {

            }
        }
    }
}